import os
import json
from graph_analyzer.graph import Graph, find_boundary_nodes
from graph_analyzer.graph_parser import Parser
from graph_analyzer.bind import bind_code_info_for_data, write_to_csv

def serialize_domain_structure(domain_structure):
    serialized_structure = {}
    for domain, data in domain_structure.items():
        serialized_structure[domain] = {
            'boundary': {'upper': list(data['boundary']['upper']), 'lower': list(data['boundary']['lower'])},
            'nodes': [node.name for node in data['nodes']]
        }
        # 递归处理子域，避免解析 boundary 和 nodes 部分
        for key in data:
            if key not in ['boundary', 'nodes', 'upper', 'lower']:
                serialized_structure[domain][key] = serialize_domain_structure({key: data[key]})
    return serialized_structure

def process(args):    
    ir_file_path = args.ir
    with open(ir_file_path, 'r') as f:
        input_text = f.read()

    parser = Parser()
    parser.parse(input_text)

    nodes = parser.get_nodes()
    graph = Graph(nodes)

    if args.data:
        bind_result = bind_code_info_for_data(args.data, nodes)
        if bind_result:
            # 将 append 参数传递给 write_to_csv
            write_to_csv(bind_result, args.output, args.append)

    domain_structure = find_boundary_nodes(nodes.values(), 1)
    output_structure = serialize_domain_structure(domain_structure)
    with open(os.path.join(args.output, "struct.json"), "w") as f:
        json.dump(output_structure, f, ensure_ascii=False, indent=4)
    if args.node_list:
        node_set_path = args.node_list
        if not os.path.exists(node_set_path):
            logging.error("The json of nodes information does not exist! Path: %s", node_set_path)
            return
        with open(node_set_path, 'r', encoding='utf-8') as file:
            scope_list = [line.strip() for line in file if line.strip()]
        result = graph.find_independent_nodes(scope_list)
        final_res = [ii.scope for ii in result]
        with open(os.path.join(args.output, "first.txt"), 'w') as f:
            f.write('\n'.join(final_res))